'''
Created on Mar 23, 2011

@author: mwarren1
'''
import os.path
import wx
from wx.lib.scrolledpanel import ScrolledPanel
from wx.tools.dbg import Logger

import resources

import maildroplibs
import TaskBarIcon
import CommandDialog
import StartupSettings

debug = Logger('SettingsGUI')
debug.SetStream(maildroplibs.DEBUGSTREAM)
debug(enable = maildroplibs.ENABLEDEBUG)

class SettingsGUI(wx.Frame):
    '''
    classdocs
    '''


    def __init__(self, settings):
        '''
        Constructor
        '''        
        self.settings = settings
                
        winSize = wx.Size(420,480)
        textCtrlSize = wx.Size(150,-1)
        self.downloadFolderCtrlSize = wx.Size(220,-1)
        
        if 'wxGTK' in wx.PlatformInfo:
            winSize = wx.Size(430,490)
            textCtrlSize = wx.Size(175,-1)
            self.downloadFolderCtrlSize = wx.Size(235,-1)
        elif 'wxMac' in wx.PlatformInfo:
            winSize = wx.Size(450,490)
            textCtrlSize = wx.Size(175,-1)
            #TODO: Determine size needed for download folder text field
            # to fill whole frame
            self.downloadFolderCtrlSize = wx.Size(220,-1)
       
                        
        wx.Frame.__init__(self, None, title = "MailDrop Settings", size=winSize, style=wx.SYSTEM_MENU|wx.CAPTION|wx.CLOSE_BOX|wx.CLIP_CHILDREN)
        icon = resources.MakeIcon(resources.getBoxIconImage())
        self.SetIcon(icon)
        
        if 'wxMac' in wx.PlatformInfo:
            menu_bar = wx.MenuBar()
            help_menu = wx.Menu()
            
            help_menu.Append(wx.ID_ABOUT, "&About MailDrop")
            menu_bar.Append(help_menu, "&Help")
            self.SetMenuBar(menu_bar)
            self.Bind(wx.EVT_MENU, TaskBarIcon.showAbout)
        
        ''' Create Settings Window '''
        framePanel = wx.Panel(self)
        notebook = wx.Notebook(framePanel, -1, size=(winSize.x-20, winSize.y-80), style=wx.BK_DEFAULT)
        
        ''' Email Settings '''
        emailPanel = wx.Panel(notebook)
        emailPanelSizer = wx.BoxSizer(wx.VERTICAL)
        
        emailLoginStaticBoxSizer = wx.StaticBoxSizer(wx.StaticBox(emailPanel, -1, "Login"), wx.HORIZONTAL)
        emailLoginSizer = wx.FlexGridSizer(cols = 2, vgap = 10, hgap = 10)
        
        emailStartupStaticBoxSizer = wx.StaticBoxSizer(wx.StaticBox(emailPanel, -1, ""))
                        
        usernameLABEL = wx.StaticText(emailPanel, -1, "Username:")
        self.usernameINPUT = wx.TextCtrl(emailPanel, -1, size = textCtrlSize)
        passwordLABEL = wx.StaticText(emailPanel, -1, "Password:")
        self.passwordINPUT = wx.TextCtrl(emailPanel, -1, style=wx.TE_PASSWORD, size = textCtrlSize)
        
        emailServerStaticBoxSizer = wx.StaticBoxSizer(wx.StaticBox(emailPanel, -1, "Connection"), wx.HORIZONTAL)
        emailServerSizer = wx.FlexGridSizer(cols = 2, vgap = 10, hgap = 10)
        
        emailserverLABEL = wx.StaticText(emailPanel, -1, "Server:")
        self.emailserverINPUT = wx.TextCtrl(emailPanel, -1, size = textCtrlSize)
        imapportLABEL = wx.StaticText(emailPanel, -1, "Port:")
        self.imapportINPUT = wx.SpinCtrl(emailPanel, -1, size = (65, -1), min = 1, max = 99999)
        self.sslINPUT = wx.CheckBox(emailPanel, -1, "Login using SSL")
        self.sslINPUT.SetValue(True)
        
        self.systemstartupINPUT = wx.CheckBox(emailPanel, -1, "Run at System Startup")
        self.systemstartupINPUT.SetValue(False)
        if 'wxMac' in wx.PlatformInfo:
            self.systemstartupINPUT.Enable(False)
        
        ''' Email Sizer '''

        emailLoginSizer.Add(usernameLABEL, 0, wx.ALIGN_RIGHT)
        emailLoginSizer.Add(self.usernameINPUT)
        emailLoginSizer.Add(passwordLABEL, 0, wx.ALIGN_RIGHT)
        emailLoginSizer.Add(self.passwordINPUT)
        emailLoginStaticBoxSizer.Add(emailLoginSizer, 0, wx.ALL, 10) 
        
        emailServerSizer.Add(emailserverLABEL, 0, wx.ALIGN_RIGHT)
        emailServerSizer.Add(self.emailserverINPUT)
        emailServerSizer.Add(imapportLABEL, 0, wx.ALIGN_RIGHT)
        emailServerSizer.Add(self.imapportINPUT)
        emailServerSizer.AddStretchSpacer()
        emailServerSizer.Add(self.sslINPUT)
        emailServerStaticBoxSizer.Add(emailServerSizer,0, wx.ALL, 10)
        
        emailStartupStaticBoxSizer.AddSpacer(10)
        emailStartupStaticBoxSizer.Add(self.systemstartupINPUT, 0, wx.ALL, 10)
        
        emailPanelSizer.Add(emailLoginStaticBoxSizer,0, wx.EXPAND|wx.ALIGN_TOP|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        emailPanelSizer.Add(emailServerStaticBoxSizer, 0, wx.EXPAND|wx.ALIGN_TOP|wx.LEFT|wx.RIGHT|wx.TOP, 10)
        emailPanelSizer.Add(emailStartupStaticBoxSizer, 0, wx.EXPAND|wx.ALIGN_TOP|wx.LEFT|wx.RIGHT|wx.TOP, 10)  
        emailPanel.SetSizer(emailPanelSizer)
        notebook.AddPage(emailPanel, "Email")
        
        ''' Download Settings '''
        downloadPanel = wx.Panel(notebook)
        
        downloadPanelSizer = wx.BoxSizer(wx.VERTICAL)
        downloadStaticBoxSizer = wx.StaticBoxSizer(wx.StaticBox(downloadPanel, -1, ""), wx.VERTICAL)
        self.downloadSizer = wx.BoxSizer(wx.VERTICAL)        
        downloadLocationStaticBoxSizer = wx.StaticBoxSizer(wx.StaticBox(downloadPanel, -1, ""), wx.VERTICAL)
        downloadLocationSizer = wx.BoxSizer(wx.HORIZONTAL)

        self.downloadLabelPanel = ScrolledPanel(downloadPanel, -1, size = (-1, 230), style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)

        self.exitButtons = []
        self.emaillabelLABELs = []
        self.emaillabelINPUTs = []
        self.downloadfolderLABELs = []
        self.downloadfolderINPUTs = []
        self.downloadbrowseBUTTONs = []
        self.overwriteINPUTs = []
        self.commandsBUTTONs = []
        self.emaillabelSizerBoxes = []
        
        for i in range(len(self.settings['LABELDICT'])):
            self.emaillabelSizerBoxes.append(wx.StaticBoxSizer(wx.StaticBox(self.downloadLabelPanel, -1, ""), wx.VERTICAL))
            labelsizer = wx.FlexGridSizer(cols = 3, vgap = 10, hgap = 5)   
        
            ''' Create Controls '''
            self.exitButtons.append(wx.Button(self.downloadLabelPanel, wx.ID_REMOVE+i, "x", style = wx.BU_EXACTFIT|wx.NO_BORDER))
            self.exitButtons[-1].Bind(wx.EVT_BUTTON, self.onRemoveLabel)
            self.emaillabelLABELs.append(wx.StaticText(self.downloadLabelPanel, -1, "Label:"))
            self.emaillabelINPUTs.append(wx.TextCtrl(self.downloadLabelPanel, -1))
            self.downloadfolderLABELs.append(wx.StaticText(self.downloadLabelPanel, -1, "Folder:"))
            self.downloadfolderINPUTs.append(wx.TextCtrl(self.downloadLabelPanel, -1, size = self.downloadFolderCtrlSize))
            self.downloadbrowseBUTTONs.append(wx.Button(self.downloadLabelPanel, wx.ID_FIND+i, "..", style = wx.BU_EXACTFIT))
            self.downloadbrowseBUTTONs[-1].Bind(wx.EVT_BUTTON, self.onBrowseButton)
            self.overwriteINPUTs.append(wx.CheckBox(self.downloadLabelPanel, -1, "Overwrite Files"))
            self.overwriteINPUTs[-1].SetValue(True)
            if maildroplibs.TYPE:
                self.commandsBUTTONs.append(wx.Button(self.downloadLabelPanel, wx.ID_SETUP+i, "Commands", style = wx.BU_EXACTFIT))
                self.commandsBUTTONs[-1].Bind(wx.EVT_BUTTON, self.onCommandButton)
            
            ''' Add to Sizer '''
            labelsizer.AddStretchSpacer()
            labelsizer.AddStretchSpacer()
            labelsizer.Add(self.exitButtons[i], 0, wx.ALIGN_RIGHT)
            
            labelsizer.Add(self.emaillabelLABELs[i], 0, wx.ALIGN_RIGHT|wx.LEFT, 10)
            labelsizer.Add(self.emaillabelINPUTs[i], 0)
            labelsizer.AddStretchSpacer()
            
            labelsizer.Add(self.downloadfolderLABELs[i], 0, wx.ALIGN_RIGHT)
            labelsizer.Add(self.downloadfolderINPUTs[i])
            labelsizer.Add(self.downloadbrowseBUTTONs[i])
            
            labelsizer.AddStretchSpacer()
            labelsizer.Add(self.overwriteINPUTs[i])   
            labelsizer.AddStretchSpacer()
            
            labelsizer.AddStretchSpacer()
            if maildroplibs.TYPE:
                labelsizer.Add(self.commandsBUTTONs[i])
            labelsizer.AddStretchSpacer()
            
            labelsizer.AddStretchSpacer()
            labelsizer.AddStretchSpacer() 
            labelsizer.AddStretchSpacer()  
            
            self.emaillabelSizerBoxes[i].Add(labelsizer)
            
            self.downloadSizer.Add(self.emaillabelSizerBoxes[i], 0, wx.ALL, 5)
            
        addlabelBUTTON = wx.Button(downloadPanel, -1, "Add Label")
        addlabelBUTTON.Bind(wx.EVT_BUTTON, self.onAddLabel)
        
        checkintervalLABEL = wx.StaticText(downloadPanel, -1, "Check Every x Minutes: ")
        self.checkintervalINPUT = wx.SpinCtrl(downloadPanel, -1, size = (50, -1), min = 1, max = 120)

        downloadLocationSizer.Add(checkintervalLABEL, 0, wx.ALIGN_RIGHT)
        downloadLocationSizer.Add(self.checkintervalINPUT)
        
        self.downloadLabelPanel.SetSizer(self.downloadSizer)
        self.downloadLabelPanel.SetupScrolling()
        
        downloadStaticBoxSizer.Add(self.downloadLabelPanel, 0, wx.EXPAND|wx.ALL, 10)
        downloadStaticBoxSizer.Add(addlabelBUTTON, 0, wx.ALIGN_RIGHT)
        downloadPanelSizer.Add(downloadStaticBoxSizer, 0, wx.EXPAND|wx.ALIGN_TOP|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        
        downloadLocationStaticBoxSizer.Add(downloadLocationSizer, 0, wx.ALL, 10)
        downloadPanelSizer.Add(downloadLocationStaticBoxSizer, 0, wx.EXPAND|wx.ALIGN_TOP|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        
        downloadPanel.SetSizer(downloadPanelSizer)
        notebook.AddPage(downloadPanel, "Download")
        
        ''' Proxy Settings '''
        proxyPanel = wx.Panel(notebook)
        
        proxyPanelSizer = wx.BoxSizer(wx.VERTICAL)
        proxyStaticBoxSizer = wx.StaticBoxSizer(wx.StaticBox(proxyPanel, -1, ""), wx.VERTICAL)
        proxySizer = wx.BoxSizer(wx.VERTICAL) 
        proxyOptionsSizer = wx.FlexGridSizer(cols = 2, vgap = 10, hgap = 10)
        
        proxyOptionsPanel = ScrolledPanel(proxyPanel, -1, size = (-1,230), style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)

        self.noProxyRadio = wx.RadioButton(proxyPanel, -1, "No proxy server", style = wx.RB_GROUP)
        self.defaultProxyRadio = wx.RadioButton(proxyPanel, -1, "Auto-detect proxy settings")
        self.manualProxyRadio = wx.RadioButton(proxyPanel, -1, "Manually enter proxy settings")
        
        imapproxyenabledLABEL = wx.StaticText(proxyOptionsPanel, -1, "Enable Email Proxy:")
        self.imapproxyenabledINPUT = wx.CheckBox(proxyOptionsPanel, -1, "")
        imapproxytypeLABEL = wx.StaticText(proxyOptionsPanel, -1, "Proxy Type:")
        self.imapproxytypeINPUT = wx.Choice(proxyOptionsPanel, -1, choices = ["SOCKS4","SOCKS5","HTTP"]) # Default Ports: 1080, 1080, 8080
        imapproxyurlLABEL = wx.StaticText(proxyOptionsPanel, -1, "Proxy URL:")
        self.imapproxyurlINPUT = wx.TextCtrl(proxyOptionsPanel, -1, size = textCtrlSize)
        imapproxyportLABEL = wx.StaticText(proxyOptionsPanel, -1, "Proxy Port:")
        self.imapproxyportINPUT = wx.SpinCtrl(proxyOptionsPanel, -1, size = (65, -1), min = 1, max = 99999)
        imapproxyusernameLABEL = wx.StaticText(proxyOptionsPanel, -1, "Username:")
        self.imapproxyusernameINPUT = wx.TextCtrl(proxyOptionsPanel, -1, size = textCtrlSize)
        imapproxypasswordLABEL = wx.StaticText(proxyOptionsPanel, -1, "Password:")
        self.imapproxypasswordINPUT = wx.TextCtrl(proxyOptionsPanel, -1, style=wx.TE_PASSWORD, size = textCtrlSize)
        

        httpproxyenabledLABEL = wx.StaticText(proxyOptionsPanel, -1, "Enable HTTP Proxy:")
        self.httpproxyenabledINPUT = wx.CheckBox(proxyOptionsPanel, -1, "")
        httpproxyurlLABEL = wx.StaticText(proxyOptionsPanel, -1, "Proxy URL:")
        self.httpproxyurlINPUT = wx.TextCtrl(proxyOptionsPanel, -1, size = textCtrlSize)
        httpproxyportLABEL = wx.StaticText(proxyOptionsPanel, -1, "Proxy Port:") # Default: 8080
        self.httpproxyportINPUT = wx.SpinCtrl(proxyOptionsPanel, -1, size = (65, -1), min = 1, max = 99999)
        httpproxyusernameLABEL = wx.StaticText(proxyOptionsPanel, -1, "Username:")
        self.httpproxyusernameINPUT = wx.TextCtrl(proxyOptionsPanel, -1, size = textCtrlSize)
        httpproxypasswordLABEL = wx.StaticText(proxyOptionsPanel, -1, "Password:")
        self.httpproxypasswordINPUT = wx.TextCtrl(proxyOptionsPanel, -1, style=wx.TE_PASSWORD, size = textCtrlSize)

        self.imapproxyenabledINPUT.Bind(wx.EVT_CHECKBOX, self.onImapProxyCheck)
        self.httpproxyenabledINPUT.Bind(wx.EVT_CHECKBOX, self.onHttpProxyCheck)
        
        ''' Proxy Sizer '''
   
        radioBorder = 5
        if 'wxGTK' in wx.PlatformInfo:
            radioBorder = 0
        
        proxySizer.Add(self.noProxyRadio, 0, wx.ALL, radioBorder)
        proxySizer.Add(self.defaultProxyRadio, 0, wx.ALL, radioBorder)
        proxySizer.Add(self.manualProxyRadio, 0, wx.ALL, radioBorder)
        
        proxyOptionsSizer.Add(imapproxyenabledLABEL, 0, wx.ALIGN_RIGHT|wx.LEFT|wx.TOP, 10)
        proxyOptionsSizer.Add(self.imapproxyenabledINPUT, 0, wx.TOP, 10)
        proxyOptionsSizer.Add(imapproxytypeLABEL, 0, wx.ALIGN_RIGHT)
        proxyOptionsSizer.Add(self.imapproxytypeINPUT)
        proxyOptionsSizer.Add(imapproxyurlLABEL, 0, wx.ALIGN_RIGHT)
        proxyOptionsSizer.Add(self.imapproxyurlINPUT)
        proxyOptionsSizer.Add(imapproxyportLABEL, 0, wx.ALIGN_RIGHT)
        proxyOptionsSizer.Add(self.imapproxyportINPUT)
        proxyOptionsSizer.Add(imapproxyusernameLABEL, 0, wx.ALIGN_RIGHT)
        proxyOptionsSizer.Add(self.imapproxyusernameINPUT)
        proxyOptionsSizer.Add(imapproxypasswordLABEL, 0, wx.ALIGN_RIGHT)
        proxyOptionsSizer.Add(self.imapproxypasswordINPUT)
        
        proxyOptionsSizer.Add(httpproxyenabledLABEL, 0, wx.ALIGN_RIGHT)
        proxyOptionsSizer.Add(self.httpproxyenabledINPUT)
        proxyOptionsSizer.Add(httpproxyurlLABEL, 0, wx.ALIGN_RIGHT)
        proxyOptionsSizer.Add(self.httpproxyurlINPUT)
        proxyOptionsSizer.Add(httpproxyportLABEL, 0, wx.ALIGN_RIGHT)
        proxyOptionsSizer.Add(self.httpproxyportINPUT)
        proxyOptionsSizer.Add(httpproxyusernameLABEL, 0, wx.ALIGN_RIGHT)
        proxyOptionsSizer.Add(self.httpproxyusernameINPUT)
        proxyOptionsSizer.Add(httpproxypasswordLABEL, 0, wx.ALIGN_RIGHT)
        proxyOptionsSizer.Add(self.httpproxypasswordINPUT)
        
        proxyOptionsPanel.SetSizer(proxyOptionsSizer)
        proxyOptionsPanel.SetupScrolling()
        
        proxyStaticBoxSizer.Add(proxySizer, 0, wx.ALL, 10)
        proxyStaticBoxSizer.Add(proxyOptionsPanel, 0, wx.EXPAND|wx.ALIGN_RIGHT|wx.ALL, 10)
        #proxyStaticBoxSizer.Add(proxyOptionsSizer, 0, wx.ALL, 10)
        proxyPanelSizer.Add(proxyStaticBoxSizer, 0, wx.EXPAND|wx.ALIGN_TOP|wx.LEFT|wx.RIGHT|wx.TOP, border=10) 
        
        proxyPanel.SetSizer(proxyPanelSizer)
        notebook.AddPage(proxyPanel, "Proxies")
        
        ''' Button Sizer '''
        buttonSizer = wx.StdDialogButtonSizer()
        
        okBUTTON = wx.Button(framePanel, wx.ID_OK, "OK")
        okBUTTON.SetDefault()
        cancelBUTTON = wx.Button(framePanel, wx.ID_CANCEL, "Cancel")
        applyBUTTON = wx.Button(framePanel, wx.ID_APPLY, "Apply")

        buttonSizer.AddButton(okBUTTON)
        buttonSizer.AddButton(cancelBUTTON)
        buttonSizer.AddButton(applyBUTTON)
        buttonSizer.Realize()

        boxSizer = wx.BoxSizer(wx.VERTICAL)
        boxSizer.Add(notebook,0, wx.ALL, 5)
        boxSizer.Add(buttonSizer, 0, wx.ALIGN_RIGHT|wx.ALL, 8)
        
        framePanel.SetSizer(boxSizer)
        
        ''' Bindings '''
        self.Bind(wx.EVT_RADIOBUTTON, self.onRadioSelect)        
        okBUTTON.Bind(wx.EVT_BUTTON, self.storeFields)
        cancelBUTTON.Bind(wx.EVT_BUTTON, self.OnClose)
        applyBUTTON.Bind(wx.EVT_BUTTON, self.storeFields)        
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_SHOW, self.OnShow)
        
        self.populateFields()
        
    def populateFields(self):
        self.__populateField('usernameINPUT', 'USERNAME') #self.usernameINPUT.SetValue(self.settings['USERNAME'] if self.settings['USERNAME'] is not None else "")
        self.passwordINPUT.SetValue(self.settings.getpassword() if self.settings['PASSWORD'] is not None else "")
        self.__populateField('emailserverINPUT','EMAILSERVER')
        if self.settings['SSL']:
            self.__populateField('imapportINPUT','IMAPSSLPORT',True)
        else:
            self.__populateField('imapportINPUT','IMAPPORT',True)
        self.__populateField('sslINPUT','SSL')
        
        self.__populateField('systemstartupINPUT', 'SYSTEMSTARTUP')
        
        i = 0
        for label, info in self.settings['LABELDICT'].items():
            folder = info[0]
            overwrite = info[1]
            self.emaillabelINPUTs[i].SetValue(label)
            self.downloadfolderINPUTs[i].SetValue(folder)
            self.overwriteINPUTs[i].SetValue(overwrite)
            i += 1
        
        self.__populateField('checkintervalINPUT','CHECKINTERVAL',True)
                    
        enableProxy = False
        if(self.settings['PROXY'] == maildroplibs.PROXY_OFF):
            self.noProxyRadio.SetValue(True)
            self.defaultProxyRadio.SetValue(False)
            self.manualProxyRadio.SetValue(False)
            enableProxy = False
        elif(self.settings['PROXY'] == maildroplibs.PROXY_AUTO):
            self.noProxyRadio.SetValue(False)
            self.defaultProxyRadio.SetValue(True)
            self.manualProxyRadio.SetValue(False)
            enableProxy = False
        elif(self.settings['PROXY'] == maildroplibs.PROXY_MAN):
            self.noProxyRadio.SetValue(False)
            self.defaultProxyRadio.SetValue(False)
            self.manualProxyRadio.SetValue(True)
            enableProxy = True
        
        self.__populateField('imapproxyenabledINPUT','IMAPPROXYENABLED')
        #self.__populateField('imapproxytypeINPUT','IMAPPROXYTYPE', True)
        if self.settings['IMAPPROXYTYPE'] is not None:
            self.imapproxytypeINPUT.SetSelection(self.settings['IMAPPROXYTYPE']-1)
        else:
            self.imapproxytypeINPUT.SetSelection(0)
        self.__populateField('imapproxyurlINPUT','IMAPPROXYURL')
        self.__populateField('imapproxyportINPUT','IMAPPROXYPORT',True)
        self.__populateField('imapproxyusernameINPUT','IMAPPROXYUSERNAME')
        self.imapproxypasswordINPUT.SetValue(self.settings.getimapproxypassword() if self.settings['IMAPPROXYPASSWORD'] is not None else "")
        
        enableImapProxy = (enableProxy and self.imapproxyenabledINPUT.GetValue())
        
        self.imapproxyenabledINPUT.Enable(enableProxy)
        self.imapproxytypeINPUT.Enable(enableImapProxy)
        self.imapproxyurlINPUT.Enable(enableImapProxy)
        self.imapproxyportINPUT.Enable(enableImapProxy)
        self.imapproxyusernameINPUT.Enable(enableImapProxy)
        self.imapproxypasswordINPUT.Enable(enableImapProxy)
        
        self.__populateField('httpproxyenabledINPUT','HTTPPROXYENABLED')
        self.__populateField('httpproxyurlINPUT','HTTPPROXYURL')
        self.__populateField('httpproxyportINPUT','HTTPPROXYPORT',True)
        self.__populateField('httpproxyusernameINPUT','HTTPPROXYUSERNAME')
        self.httpproxypasswordINPUT.SetValue(self.settings.gethttpproxypassword() if self.settings['HTTPPROXYPASSWORD'] is not None else "")
        
        enablehttpProxy = (enableProxy and self.httpproxyenabledINPUT.GetValue()) 
        
        self.httpproxyenabledINPUT.Enable(enableProxy)
        self.httpproxyurlINPUT.Enable(enablehttpProxy)
        self.httpproxyportINPUT.Enable(enablehttpProxy)
        self.httpproxyusernameINPUT.Enable(enablehttpProxy)
        self.httpproxypasswordINPUT.Enable(enablehttpProxy)
        
    def storeFields(self, event):
        self.settings.firstrun = False
        try:            
            self.__storeField('usernameINPUT', 'USERNAME') #self.settings['USERNAME'] = self.usernameINPUT.GetValue() if self.usernameINPUT.GetValue() != "" else None
            self.settings.setpassword(self.passwordINPUT.GetValue()if self.passwordINPUT.GetValue() != "" else None)
            self.__storeField('emailserverINPUT', 'EMAILSERVER')
            if self.settings['SSL']:
                self.__storeField('imapportINPUT', 'IMAPSSLPORT', True)
            else:
                self.__storeField('imapportINPUT', 'IMAPPORT', True)
            self.__storeField('sslINPUT', 'SSL')
            
            self.__storeField('systemstartupINPUT', 'SYSTEMSTARTUP')
            
            for i in range(len(self.emaillabelINPUTs)):
                label = self.emaillabelINPUTs[i].GetValue()
                folder = self.downloadfolderINPUTs[i].GetValue()
                overwrite = self.overwriteINPUTs[i].GetValue()
                
                commands = ''
                if label in self.settings['LABELDICT']:
                    commands = self.settings['LABELDICT'][label][2] 
                                
                labelParams = [folder, overwrite, commands]
                self.settings['LABELDICT'][label] = labelParams
                
            self.__storeField('checkintervalINPUT', 'CHECKINTERVAL', True)
            
            if self.noProxyRadio.GetValue():
                self.settings['PROXY'] = maildroplibs.PROXY_OFF
            elif self.defaultProxyRadio.GetValue():
                self.settings['PROXY'] = maildroplibs.PROXY_AUTO
            elif self.manualProxyRadio.GetValue():
                self.settings['PROXY'] = maildroplibs.PROXY_MAN
                
            debug('PROXY is being stored as ' + str(self.settings['PROXY']))
            
            self.__storeField('imapproxyenabledINPUT', 'IMAPPROXYENABLED')
            #self.__storeField('imapproxytypeINPUT', 'IMAPPROXYTYPE', True)
            self.settings['IMAPPROXYTYPE'] = self.imapproxytypeINPUT.GetCurrentSelection()+1
            self.__storeField('imapproxyurlINPUT', 'IMAPPROXYURL')
            self.__storeField('imapproxyportINPUT', 'IMAPPROXYPORT', True)
            self.__storeField('imapproxyusernameINPUT', 'IMAPPROXYUSERNAME')
            self.settings.setimapproxypassword(self.imapproxypasswordINPUT.GetValue() if self.imapproxypasswordINPUT.GetValue() != "" else None)
            
            self.__storeField('httpproxyenabledINPUT', 'HTTPPROXYENABLED')
            self.__storeField('httpproxyurlINPUT', 'HTTPPROXYURL')
            self.__storeField('httpproxyportINPUT', 'HTTPPROXYPORT', True)
            self.__storeField('httpproxyusernameINPUT', 'HTTPPROXYUSERNAME')
            self.settings.sethttpproxypassword(self.httpproxypasswordINPUT.GetValue() if self.httpproxypasswordINPUT.GetValue() != "" else None)
            
            self.settings.verify()
            
            print "Saving Settings:"
            print self.settings
            self.settings.save()
            
            ''' perform startup change '''
            StartupSettings.enableStartup(self.systemstartupINPUT.GetValue()) 
            
            maildroplibs.MailThread.unpause()
            TaskBarIcon.setToolTip("")
            
            if event.GetId() == wx.ID_OK:
                self.Hide() 
            
        except maildroplibs.SettingsError as e:
            TaskBarIcon.setToolTip("Error Running MailDrop\nPlease Check Settings", TaskBarIcon.ERROR_ICON)
            e.showError(self)
 
    def onAddLabel(self, event):
        self.emaillabelSizerBoxes.append(wx.StaticBoxSizer(wx.StaticBox(self.downloadLabelPanel, -1, ""), wx.VERTICAL))
        labelsizer = wx.FlexGridSizer(cols = 3, vgap = 10, hgap = 5) 
    
        i = len(self.emaillabelINPUTs)
                        
        ''' Create Controls '''
        self.exitButtons.append(wx.Button(self.downloadLabelPanel, wx.ID_REMOVE+i, "x", style = wx.BU_EXACTFIT|wx.NO_BORDER))
        self.exitButtons[-1].Bind(wx.EVT_BUTTON, self.onRemoveLabel)
        self.emaillabelLABELs.append(wx.StaticText(self.downloadLabelPanel, -1, "Label:"))
        self.emaillabelINPUTs.append(wx.TextCtrl(self.downloadLabelPanel, -1))
        self.downloadfolderLABELs.append(wx.StaticText(self.downloadLabelPanel, -1, "Folder:"))
        self.downloadfolderINPUTs.append(wx.TextCtrl(self.downloadLabelPanel, -1, size = self.downloadFolderCtrlSize, value = self.settings.getDropboxLocation()))
        self.downloadbrowseBUTTONs.append(wx.Button(self.downloadLabelPanel, wx.ID_FIND+i, "..", style = wx.BU_EXACTFIT))
        self.downloadbrowseBUTTONs[-1].Bind(wx.EVT_BUTTON, self.onBrowseButton)
        self.overwriteINPUTs.append(wx.CheckBox(self.downloadLabelPanel, -1, "Overwrite Files"))
        self.overwriteINPUTs[-1].SetValue(True)
        if maildroplibs.TYPE:
            self.commandsBUTTONs.append(wx.Button(self.downloadLabelPanel, wx.ID_SETUP+i, "Commands", style = wx.BU_EXACTFIT))
            self.commandsBUTTONs[-1].Bind(wx.EVT_BUTTON, self.onCommandButton)

        ''' Add to Sizer '''
        labelsizer.AddStretchSpacer()
        labelsizer.AddStretchSpacer()
        labelsizer.Add(self.exitButtons[-1], 0, wx.ALIGN_RIGHT)
        
        labelsizer.Add(self.emaillabelLABELs[-1], 0, wx.ALIGN_RIGHT|wx.LEFT, 10)
        labelsizer.Add(self.emaillabelINPUTs[-1], 0)
        labelsizer.AddStretchSpacer()
        
        labelsizer.Add(self.downloadfolderLABELs[-1], 0, wx.ALIGN_RIGHT)
        labelsizer.Add(self.downloadfolderINPUTs[-1])
        labelsizer.Add(self.downloadbrowseBUTTONs[-1])
        
        labelsizer.AddStretchSpacer()
        labelsizer.Add(self.overwriteINPUTs[-1])  
        labelsizer.AddStretchSpacer() 
        
        labelsizer.AddStretchSpacer()
        if maildroplibs.TYPE:
            labelsizer.Add(self.commandsBUTTONs[-1])
        labelsizer.AddStretchSpacer()
        
        labelsizer.AddStretchSpacer()
        labelsizer.AddStretchSpacer() 
        labelsizer.AddStretchSpacer() 
        
        self.emaillabelSizerBoxes[-1].Add(labelsizer)
        self.downloadSizer.Add(self.emaillabelSizerBoxes[-1], 0, wx.ALL, 5)
        
        self.downloadLabelPanel.SetSizer(self.downloadSizer)
        self.downloadLabelPanel.SetupScrolling(scrollToTop = False)
        self.downloadLabelPanel.ScrollChildIntoView(self.overwriteINPUTs[-1])
         
    def onRemoveLabel(self, event):
        labelNum = int(event.GetId() - wx.ID_REMOVE)
        label = self.emaillabelINPUTs[labelNum].GetValue()
        
        debug(str(labelNum) + ": " + label)
        
        if label in self.settings['LABELDICT']:
            del self.settings['LABELDICT'][label]
        
        self.exitButtons[labelNum].Destroy()
        self.emaillabelLABELs[labelNum].Destroy()
        self.emaillabelINPUTs[labelNum].Destroy()
        self.downloadfolderLABELs[labelNum].Destroy()
        self.downloadfolderINPUTs[labelNum].Destroy()
        self.overwriteINPUTs[labelNum].Destroy()
        if maildroplibs.TYPE:
            self.commandsBUTTONs[labelNum].Destroy()
        self.downloadSizer.Remove(self.emaillabelSizerBoxes[labelNum])
        
        
        self.downloadLabelPanel.SetSizer(self.downloadSizer)
        self.downloadLabelPanel.SetupScrolling(scrollToTop = False)  
        
        del self.exitButtons[labelNum]
        del self.emaillabelLABELs[labelNum]
        del self.emaillabelINPUTs[labelNum]
        del self.downloadfolderLABELs[labelNum]
        del self.downloadfolderINPUTs[labelNum]
        del self.overwriteINPUTs[labelNum]
        if maildroplibs.TYPE:
            del self.commandsBUTTONs[labelNum]
        del self.emaillabelSizerBoxes[labelNum]
    
    def onBrowseButton(self, event):
        labelNum = int(event.GetId() - wx.ID_FIND)
        debug("Browsing for label number " + str(labelNum))
        startDir = self.downloadfolderINPUTs[labelNum].GetValue()
        #If starting directory does not exist, 
        #iterate down until an existing parent directory is found
        while (not os.path.exists(startDir) and (startDir != '')):
            startDir = os.path.split(startDir)[0]
        debug("Starting Dir is " + startDir)
        browser = wx.DirDialog(self, "Choose a Download Folder", defaultPath = startDir)
        result = browser.ShowModal()
        if result == wx.ID_OK:
            selectedDir = browser.GetPath()
            debug("Selected Path: " + selectedDir)
            self.downloadfolderINPUTs[labelNum].SetValue(selectedDir)
        browser.Destroy()
 
    def onCommandButton(self, event):
        labelNum = int(event.GetId() - wx.ID_SETUP)
        label = self.emaillabelINPUTs[labelNum].GetValue()
        folder = self.downloadfolderINPUTs[labelNum].GetValue()
        overwrite = self.overwriteINPUTs[labelNum].GetValue()
        
        if label != '' and folder != '':
            if label not in self.settings['LABELDICT']:
                self.settings['LABELDICT'][label] = [folder, overwrite, '']
            
            commandText = self.settings['LABELDICT'][label][2]
            
            debug(str(labelNum) + ": " + label)
            
    #        dlg = wx.TextEntryDialog(self, 'Enter commands to be run after emails downloaded from label "' + label + '"\n(One command per line)', 'Commands for "' + label + '"',defaultValue = commandText, style = wx.TextEntryDialogStyle|wx.TE_MULTILINE)
            dlg = CommandDialog.CommandDialog(self, label, commandText)
            dlg.ShowModal()
            commandText = dlg.GetValue() 
            debug(commandText)
            self.settings['LABELDICT'][label][2] = commandText
            
            dlg.Destroy()
        else:
            wx.MessageDialog(self, "Label Name and Folder Must be Filled in Before Commands Can Be Set!", "Cannot Set Commands", wx.OK|wx.ICON_ERROR).ShowModal()
         
    def onRadioSelect(self, event):
        enableProxy = False
        
        if event.GetId() == self.noProxyRadio.GetId() or \
           event.GetId() == self.defaultProxyRadio.GetId():
            enableProxy = False
        elif event.GetId() == self.manualProxyRadio.GetId():
            enableProxy = True
        
        enableImapProxy = (enableProxy and self.imapproxyenabledINPUT.GetValue())
        enablehttpProxy = (enableProxy and self.httpproxyenabledINPUT.GetValue()) 
        
        self.imapproxyenabledINPUT.Enable(enableProxy)
        self.httpproxyenabledINPUT.Enable(enableProxy)
           
            
        self.imapproxytypeINPUT.Enable(enableImapProxy)
        self.imapproxyurlINPUT.Enable(enableImapProxy)
        self.imapproxyportINPUT.Enable(enableImapProxy)
        self.imapproxyusernameINPUT.Enable(enableImapProxy)
        self.imapproxypasswordINPUT.Enable(enableImapProxy)
        
        self.httpproxyurlINPUT.Enable(enablehttpProxy)
        self.httpproxyportINPUT.Enable(enablehttpProxy)
        self.httpproxyusernameINPUT.Enable(enablehttpProxy)
        self.httpproxypasswordINPUT.Enable(enablehttpProxy)
 
    def onImapProxyCheck(self, event):
        self.imapproxytypeINPUT.Enable(self.imapproxyenabledINPUT.GetValue())
        self.imapproxyurlINPUT.Enable(self.imapproxyenabledINPUT.GetValue())
        self.imapproxyportINPUT.Enable(self.imapproxyenabledINPUT.GetValue())
        self.imapproxyusernameINPUT.Enable(self.imapproxyenabledINPUT.GetValue())
        self.imapproxypasswordINPUT.Enable(self.imapproxyenabledINPUT.GetValue())
        
    def onHttpProxyCheck(self, event):
        self.httpproxyurlINPUT.Enable(self.httpproxyenabledINPUT.GetValue())
        self.httpproxyportINPUT.Enable(self.httpproxyenabledINPUT.GetValue())
        self.httpproxyusernameINPUT.Enable(self.httpproxyenabledINPUT.GetValue())
        self.httpproxypasswordINPUT.Enable(self.httpproxyenabledINPUT.GetValue())
  
    def __populateField(self, field, setting, isInt = False):
        debug(field + " is being set to " + str(self.settings[setting]))
        if not isInt:
            self.__dict__[field].SetValue(self.settings[setting] if self.settings[setting] is not None else "")
        else:
            self.__dict__[field].SetValue(int(self.settings[setting]) if self.settings[setting] is not None else 8080)
    
    def __storeField(self, field, setting, isInt = False):
        debug(setting + " is being stored as " + str(self.__dict__[field].GetValue()))
        if not isInt:
            self.settings[setting] = self.__dict__[field].GetValue() if self.__dict__[field].GetValue() != "" else None
        else:
            self.settings[setting] = int(self.__dict__[field].GetValue()) if self.__dict__[field].GetValue() != "" else None

    def OnShow(self, event):
        debug('Showing Settings Window')
        self.populateFields()

    def OnClose(self, event):
        self.Hide()

    def OnExit(self, event):
        self.Destroy()
        
if __name__ == "__main__":
    app = wx.App(False)
    gui = SettingsGUI(maildroplibs.settings.MailDropSettings())
    gui.Show()
    app.MainLoop()
